package org.sam.swing;

import java.awt.BorderLayout;
import java.io.FileReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * 解密登录信息的工具窗口
 * 
 * @author sam
 *
 */
public class JFrameJSEngine extends JFrame {

	private static final long serialVersionUID = 4499437483325533772L;

	public JFrameJSEngine() {
		super();
		this.initCompents();
	}

	/**
	 * 输入数据
	 */
	private JTextArea txtInput;

	/**
	 * 输出结果
	 */
	private JTextField txtOutput;

	/**
	 * 解密按钮
	 */
	private JButton btnGo;

	/**
	 * 当前的js解释引擎对象
	 */
	private ScriptEngine engine;

	/**
	 * 初始化控件显示
	 */
	protected void initCompents() {
		this.setLayout(new BorderLayout());
		txtInput = new JTextArea();
		this.add(txtInput, BorderLayout.CENTER);

		txtOutput = new JTextField();
		btnGo = new JButton(">>>");
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(btnGo, BorderLayout.WEST);
		panel.add(txtOutput, BorderLayout.CENTER);

		this.add(panel, BorderLayout.SOUTH);

		// 解密数据
		btnGo.addActionListener(e -> {
			ScriptEngine se = this.getEngine();
			try {
				Object r = se.eval("uncompile('" + txtInput.getText() +"')");
				txtOutput.setText(r.toString());
				
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		});
	}

	/**
	 * 获取脚本解释引擎
	 * 
	 * @return
	 */
	public ScriptEngine getEngine() {
		if (engine == null) {
			engine = new ScriptEngineManager().getEngineByName("nashorn");
			String jsFile = System.getProperty("user.dir") + "/funs.js";
			try {
				FileReader fr = new FileReader(jsFile);
				engine.eval(fr);
				fr.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return engine;
	}
	
	
	public static void main(String[] args){
		JFrameJSEngine frm = new JFrameJSEngine();
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setSize(1024, 768);
		frm.setVisible(true);
	}
}
